package com.alibaba.user.service.impl;

import com.alibaba.basic.constant.VerifyCodeConstants;
import com.alibaba.basic.exception.BusinessException;
import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.basic.util.MD5Utils;
import com.alibaba.basic.util.StrUtils;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.domain.User;
import com.alibaba.user.dto.EmailDto;
import com.alibaba.user.dto.UserDto;
import com.alibaba.user.mapper.LogininfoMapper;
import com.alibaba.user.mapper.UserMapper;
import com.alibaba.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private JavaMailSender javaMailSender;
    @Override
    @Transactional
    public void phoneRegister(UserDto userDto) {
        //手机号
        String phone = userDto.getPhone();
        //验证码
        String inputPhoneCode = userDto.getPhoneCode();
        //密码
        String password = userDto.getPassword();
        //重复密码
        String pwdRepeat = userDto.getPasswordRepeat();

        //1.校验
        //1.1.空值校验
        if(StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(inputPhoneCode)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(pwdRepeat)){
            throw new BusinessException("请输入正确的数据!!!");
        }

        //1.2两次密码是否相同
        if (!password.equals(pwdRepeat)){
            throw new BusinessException("两次密码不一致！！！");
        }

        //1.3 验证码是否过期
        Object phoneCode = redisTemplate.opsForValue().get(VerifyCodeConstants.REGISTER_CODE_PREFIX + phone);

        if (phoneCode == null){
            throw new BusinessException("验证码无效，请重新获取！");
        }
        //1.4 验证码是否正确
        String codeTem = phoneCode.toString().split(":")[0];
        if (!codeTem.equalsIgnoreCase(inputPhoneCode)){
            throw new BusinessException("验证码错误");
        }

        //保存数据
        //先保存t_logininfo
        User user = userDto2user(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.add(logininfo);
        System.out.println(logininfo.toString());
        //再保存t_user
        user.setLogininfoId(logininfo.getId());

        //user.setLogininfo(logininfo);
        userMapper.add(user);
    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照同名属性赋值【username，email，phone，salt，password】
        BeanUtils.copyProperties(user,logininfo);
        //设置类型，设置为用户类型
        logininfo.setType(1);
        return logininfo;
    }

    /**
     * 将userDto的数据转给user
     * @param userDto
     * @return
     */
    private User userDto2user(UserDto userDto) {

        User user = new User();
        //设置用户名
        user.setUsername(userDto.getPhone());
        //设置手机号
        user.setPhone(userDto.getPhone());
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    /**
     * email登录
     * @param emailDto
     */
    @Override
    //1.校验
    //1.1.空值校验
    public void emailRegister(EmailDto emailDto) throws MessagingException {
        String email = emailDto.getEmail();
        String password = emailDto.getPassword();
        String passwordRepeat = emailDto.getPasswordRepeat();

        if (StringUtils.isEmpty(email)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("请输入正确的数据!!!");
        }

        //1.2两次密码是否相同
        if (!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致！！！");
        }


        //3.校验 - 邮箱是否被注册
        User user = userMapper.loadByEmail(email);
        if(user != null){
            throw new BusinessException("该邮件已经注册，请直接登录!");
        }

        User user1 = emailDto2user(emailDto);

        Logininfo logininfo = user2Logininfo(user1);

        logininfoMapper.add(logininfo);
        //再保存t_user
        System.out.println(logininfo.getId());
        user1.setLogininfoId(logininfo.getId());
        //user.setLogininfo(logininfo);
        //设置状态为不启用，邮箱激活后修改状态为1(启用)
        user1.setState(0);
        userMapper.add(user1);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom("710984334@qq.com");
        //设置邮件主题
        helper.setSubject("邮件激活通知");
        //邮件正文
        helper.setText("<h1>店铺激活</h1><br>"+
                "<span>点击下面的激活链接激活店铺<br>"+
                "<a href='http://localhost:8080/user/email/active/"+user1.getId()+"'>点击激活</a>",true);
        //helper.setTo(manager.getEmail()); - 以后发给店铺入驻时的邮箱
        helper.setTo("710984334@qq.com"); //这里用我自己的邮箱做测试
        //发送消息
        javaMailSender.send(mimeMessage);
    }
    /**
     * 邮箱激活页面
     * @param id
     * @return
     */
    @Override
    public void active(Long id) {
        User user = userMapper.findOne(id);
        user.setState(1);
        userMapper.update(user);
    }


    /**
     * 将emailDto的数据转给user
     * @param emailDto
     * @return
     */
    private User emailDto2user(EmailDto emailDto) {

        User user = new User();
        //设置用户名
        user.setUsername(emailDto.getEmail());
        //设置手机号
        user.setEmail(emailDto.getEmail());
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(emailDto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    @Override
    public void update(User user) {

        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        //用户user:createtime和logoininfo_id不能修改
        //获取登录信息id
        Long logininfo_id = userMapper.findOne(user.getId()).getLogininfoId();
        //登录信息logininfo：type不修改
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setId(logininfo_id);
        logininfoMapper.update(logininfo);
        super.update(user);
    }


    @Override
    public void delete(Long id) {
        //从Logininfo_id表中用userMapper获取数据库id的LogininfoId字段
        Long logininfo_id = userMapper.findOne(id).getLogininfoId();
        //删除登录信息对象
        logininfoMapper.delete(logininfo_id);
        super.delete(id);
    }


}
